/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * <p>Project: smvc2022 - UploadController
 * <p>Powered by webrx On 2022-04-01 09:20:04
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
@Controller
public class UploadController {



    @PostMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, String user, HttpServletRequest req) {
        String msg = "上传失败，请选择一个文件";
        if (file.isEmpty()) {
            msg = "上传失败，请选择一个文件";
        } else {
            try {
                String filename = file.getOriginalFilename();
                String fileext = filename.lastIndexOf(".")==-1 ? "" : filename.toLowerCase().substring(filename.lastIndexOf("."));
                long filesize = file.getSize();
                String path = req.getServletContext().getRealPath(String.format("uploads/%tY%<tm",System.currentTimeMillis()));
                File dst = new File(path);
                if(!dst.exists()) dst.mkdirs();
                msg = "上传成功，文件：'" + filename + "'";
                file.transferTo(new File(path,filename));

            } catch (IOException e) {
                msg = "上传失败，未知错误";
            }
        }
        String result = String.format("%s:%s", user, msg);
        return result;
    }

    @PostMapping("/uploads")
    @ResponseBody
    public String uploads(MultipartFile[] file, String user, HttpServletRequest req) {
        String msg = "上传失败，请选择一个文件";

        if (file.length == 0) {
            msg = "上传失败，请选择一个文件";
        } else {
            Set<String> set = new HashSet<String>();
            for (MultipartFile fs : file) {
                if(!fs.isEmpty()) {
                    try {
                        String filename = fs.getOriginalFilename();
                        String fileext = filename.lastIndexOf(".") == -1 ? "" : filename.toLowerCase().substring(filename.lastIndexOf("."));
                        long filesize = fs.getSize();
                        String path = req.getServletContext().getRealPath(String.format("uploads/%tY%<tm", System.currentTimeMillis()));
                        File dst = new File(path);
                        if (!dst.exists()) dst.mkdirs();

                        set.add(filename);
                        fs.transferTo(new File(path, filename));

                    } catch (IOException e) {
                        msg = "上传失败，未知错误";
                    }
                }
            }
            if(set.isEmpty())  msg = "上传成功，文件：'" + set + "'";
        }
        String result = String.format("%s:%s", user, msg);
        return result;
    }

    @PostMapping("/uploadfiles")
    @ResponseBody
    public String uploadfiles( String user, MultipartHttpServletRequest req) {
        //单一文件，不符合
        //req.getFileMap().forEach((fn,mf)->{
        //    System.out.println(fn);
        //    System.out.println(mf);
        //});

        AtomicReference<String> msg = new AtomicReference<>("上传失败，");
        Set<String> set = new HashSet<String>();
        req.getMultiFileMap().forEach((fn,mf)->{
            for (Object o : mf.toArray()) {
                MultipartFile fs = (MultipartFile)o;
                if(!fs.isEmpty()) {
                    try {
                        String filename = fs.getOriginalFilename();
                        String fileext = filename.lastIndexOf(".") == -1 ? "" : filename.toLowerCase().substring(filename.lastIndexOf("."));
                        long filesize = fs.getSize();
                        String path = req.getServletContext().getRealPath(String.format("uploads/%tY%<tm", System.currentTimeMillis()));
                        File dst = new File(path);
                        if (!dst.exists()) dst.mkdirs();
                        set.add(filename);
                        fs.transferTo(new File(path, filename));
                    } catch (IOException e) {
                        msg.set("上传失败，未知错误");
                    }
                }
            }
        });
        if(!set.isEmpty())  msg.set("上传成功，文件：'" + set + "'");
        return msg.get();
    }


    @ExceptionHandler
    @ResponseBody
    public String ex(Exception ex) {
        String exs = "上传失败，";
        MaxUploadSizeExceededException me = (MaxUploadSizeExceededException) ex;
        long max = me.getMaxUploadSize();
        if (me.getMessage().contains("FileSizeLimitExceededException")) {
            exs += String.format("单个文件不能超过%dMB", max / 1024 / 1024);
        } else if (me.getMessage().contains("SizeLimitExceededException")) {
            exs += String.format("总大小不能超过%dMB", max / 1024 / 1024);
        } else {
            exs += " 未知异常";
        }
        return exs;
    }
}
